package cn.merryyou.logback.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import javax.sql.DataSource;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private DataSource dataSource;

    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    /**
     * 持久化token
     * @return
     */
    @Bean
    public JdbcTokenStore tokenStore(){
        return  new JdbcTokenStore(dataSource);
    }

    /**
     * 持久化code
     * @return
     */
    @Bean
    protected AuthorizationCodeServices authorizationCodeServices(){
        return new JdbcAuthorizationCodeServices(dataSource);
    }

    /**
     * 这里配置令牌端点(Token Endpoint)的安全约束
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {

//        security.tokenKeyAccess("permitAll()")
//                .checkTokenAccess("isAuthenticated()");
        security.passwordEncoder(passwordEncoder);
    }

    /**
     * 这里配置客户端详情服务，在这里完成客户端信息的初始化，可以在这里把客户端信息写死，也可以从数据库中获取。
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//        clients
//                .inMemory()
//                .withClient("HCMClient")
//                .secret("knovia")
//                .authorizedGrantTypes("authorization_code")
//                .scopes("user_info");
//                .autoApprove(true);


        clients.jdbc(dataSource)
                .passwordEncoder(passwordEncoder)
                .withClient("HCMClient")
                .authorizedGrantTypes("authorization_code", "client_credentials",
                        "refresh_token","password", "implicit")
                .authorities("ROLE_CLIENT")
                .resourceIds("apis")
                .scopes("read")
                .secret("knovia")
                .accessTokenValiditySeconds(300)
                .and()
                .withClient("client2")
                .authorizedGrantTypes("authorization_code", "client_credentials",
                        "refresh_token","password", "implicit")
                .authorities("ROLE_CLIENT")
                .resourceIds("apis")
                .scopes("read")
                .secret("secret2")
                .accessTokenValiditySeconds(300);
    }


    /**
     * 这里配置授权(authorization) 以及令牌(token) 的访问端和令牌服务(token service)
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

//        endpoints.authenticationManager(authenticationManager);
        endpoints.authorizationCodeServices(authorizationCodeServices())
                .authenticationManager(authenticationManager).tokenStore(tokenStore())
                .approvalStoreDisabled();
    }

}
